#$ambifile = "/data1/raw/ngs/illumina-ga-1/bioinf_int/MayoGAP/mayogap_emerge/clean/beagle_x_chr/beagle_x_ambi.tped";
#$gprobfile = "/data1/raw/ngs/illumina-ga-1/bioinf_int/MayoGAP/mayogap_emerge/clean/beagle/run_beagle/programtest/whole_chr_gprobs_dosage2";
#$ambifile = "testambi";
#$gprobfile = "testgprobs";
$ambifile = $ARGV[0];
$gprobfile =$ARGV[1];
$output = $ARGV[2];
chomp($ambifile);
chomp($gprobfile);
open ABUFF,"< $ambifile" or die "can't open $ambifile";
open BUFF,"< $gprobfile" or die "can't open $gprobfile";
open(WRBUFF,">$output");
while($line = <ABUFF>)
{
	chomp($line);
	@Aarray = split(/\s/,$line);
	$hash_ambi{$Aarray[1]} = $line;
	#print $hash_ambi{$Aarray[1]}."\n";
}	
$line = <BUFF>;
print WRBUFF $line;
while($line = <BUFF>)
{
	chomp($line);	
	@array = split(/\s/,$line);
	#print $array[0]."\n";
	if($hash_ambi{$array[0]} eq "" )
	{
		print WRBUFF $line."\n";
	}	
	else
	{
		$snpid = shift(@array);
		$geno1 = shift(@array);
		$geno2 = shift(@array);
		#print $snpid."\n";
		@Aarray = split(/\s/,$hash_ambi{$snpid});
		#print $hash_ambi{$a}."\n";
		$l = @array;
		
		shift(@Aarray);
		shift(@Aarray);
		shift(@Aarray);
		shift(@Aarray);
		$l1 = @Aarray/2;
		#print $l."\t".$l1."\n";
		if($l != $l1)
		{
			die "length of gprobs not equal to ambi tped snp length";
	
		}
		$k =0;
		for($i=0;$i<@Aarray;$i++)
		{
			$snp1 = $Aarray[$i];
			$i++;
			$snp2 =  $Aarray[$i];
			if($snp1 eq "0" || $snp2 eq "0")
			{
					
			}
			else
			{
				if($snp1  eq $geno1 && $snp2 eq $geno1)
				{
					$array[$k] = "0";
				}  
				elsif($snp1  eq $geno2 && $snp2 eq $geno2)
				{
					$array[$k] = "2";
				}
				else
				{
					$array[$k] = "1";
				}

			}
			$k++;	
		}
		$aline = join(" ",@array);
		$line = "$snpid $geno1 $geno2 $aline";
		print WRBUFF $line."\n";
	}
}
